<?php

/*
 * by jzp 747056764@qq.com
 */

namespace Account\Model;

use Common\Model\BaseModel;
use Common\Model\ModelException;
use Think\Log;
use Util\StringUtils;

class FacebookModel extends BaseModel {

    public function initFb() {
        vendor('Facebook.autoload');
        $fb = new \Facebook\Facebook([
            'app_id' => '250032338889152',
            'app_secret' => '86d8c9d2d2cc53753c40b5dee18ef8dd',
            'default_graph_version' => 'v3.0',
        ]);
        return $fb;
    }

    public function login($data) {
        $arr = parse_url($data['url_parms']);
        $queryParts = explode('&', $arr['fragment']);
        $params = array();
        foreach ($queryParts as $param) {
            $item = explode('=', $param);
            $params[$item[0]] = $item[1];
        }
        $fb = $this->initFb();
        try {
            // Returns a `Facebook\FacebookResponse` object
            $response = $fb->get('/me?fields=id,name', $params["access_token"]);
             log::record(json_encode($response),'response',true);
        } catch (Facebook\Exceptions\FacebookResponseException $e) {
//            log::record($user,'user',true);
//            echo 'Graph returned an error: ' . $e->getMessage();
            log::record(json_encode($e->getMessage()),'user',true);
            $this->errorCode($e->getMessage());
            exit;
        } catch (Facebook\Exceptions\FacebookSDKException $e) {
//            log::record($user,'user',true);
//            echo 'Facebook SDK returned an error: ' . $e->getMessage();
            log::record(json_encode($e->getMessage()),'user',true);
            $this->errorCode($e->getMessage());
            exit;
        }
        $user = $response->getGraphUser();
         log::record(json_encode($user),'user',true);
        return $user;
    }

}
